import requests
import pandas as pd
import json


def his_hq(code, year):
    url = 'https://q.stock.sohu.com/hisHq?code=cn_%s&start=%s0101&end=%s1231'
    response = requests.get(url % (code, year, year))
    return response


def save_his_stock():
    years = [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]

    a_share = pd.read_csv('D:/data/stock/A-share.csv', encoding='utf8', converters={'SYMBOL': str})

    for code in a_share.SYMBOL:
        print('code: ', code)
        for year in years:
            print('year:', year)
            response = his_hq(code, year)
            content = json.loads(response.content)
            if content.__len__() == 1 and content[0].get('hq') is not None:
                if content[0]['hq'][0].__len__() == 10:
                    df = pd.DataFrame(content[0]['hq'],
                                      columns=['日期', '开盘', '收盘', '涨跌额', '涨跌幅', '最低', '最高', '成交量(手)', '成交金额(万)', '换手率'])
                else:
                    df = pd.DataFrame(content[0]['hq'],
                                      columns=['日期', '开盘', '收盘', '涨跌额', '涨跌幅', '最低', '最高', '成交量(手)', '成交金额(万)', '换手率',
                                               ''])
                df.to_csv('D:/data/stock/%s_%s.csv' % (code, year))


if __name__ == '__main__':
    save_his_stock()
